package com.rectcircle.db

import com.rectcircle.model.{Book, Borrowal, Reader}
import org.squeryl.dsl.{ManyToMany}
import org.squeryl.PrimitiveTypeMode._


object ReaderDb{
	
	import com.rectcircle.config.LibraryDbSchema._
	def save(r:Reader) = {
		readers.insert(r)
	}
	
	def get(id:Long) = {
		readers.lookup(id)
	}
	
	def withBooks(readerWithId:Reader) = {
		readerWithId.books = borrowals.left(readerWithId).associationMap.toVector
		readerWithId
	}
	
	def findByUsername(username: String) = {
		from(readers)(r =>
			where(r.username === username)
			select(r)
		)
	}
	
	//自定义函数应用于dsl略 http://squeryl.org/custom-functions.html
	
	//类型
	/*
	val q1 =
		from(aTable)(t => select( &(t.aLong * t.aFloat) )) : Query[Double]
	
	val q2 =
		from(aTable)(t => compute( avg(t.aByte / t.anInt) )) : Query[Option[Float]]
	
	val q3 =
		from(aTable)(t => compute( t.aByte + count )) : Query[Long]
	
	val q4 =  // || is the concatenation operator :
		from(aTable)(t =>
			select( &(t.aString || t.aLong || " " || a.IntOption) )) : Query[Option[String]]
	*/
	
	//在客户端计算还是数据库计算
/*
	// the * is done on the client side :
	from(artists)(a =>
		select(a.id * 1000)
	)
	
	// in this case it is computed by the database :
	from(artists)(a =>
		select(&(a.id * 1000))
	)*/
}